//
//  CureListViewController.swift
//  HCSDK_Example
//
//  Created by hc on 2024/3/6.
//  Copyright © 2024 CocoaPods. All rights reserved.
//

import UIKit
import HCAudioPlayer
import AVFAudio
import HCTherapy

class ASMRViewController: UIViewController {
    
    let plans: String
    let duration: Int
    var cmdTitle: String = ""

    lazy var btn: UIButton = {
        let btn = UIButton(frame: .init(x: 0, y: 0, width: 100, height: 50))
        btn.backgroundColor = .blue
        btn.setTitle("idle", for: .normal)
        btn.addTarget(self, action: #selector(onPressedButton), for: .touchUpInside)
        return btn
    }()
    
    lazy var lbTime: UILabel = {
        let lb = UILabel(frame: .init(x: 0, y: 0, width: 120, height: 25))
        lb.text = "00:00"
        return lb
    }()
    
    lazy var player = {
        let player = Player()
        player.delegate = self
        return player
    }()
    
    init(plans: String, duration: Int) {
        self.plans = plans
        self.duration = duration
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        self.title = "Player"
        self.view.backgroundColor = .white
        self.view.addSubview(self.btn)
        self.btn.center = self.view.center
        
        self.view.addSubview(self.lbTime)
        self.lbTime.center = .init(x: self.view.center.x, y: self.view.center.y + 100)
        
        self.navigationItem.rightBarButtonItems = [UIBarButtonItem(
            title: "+",
            style: .plain,
            target: self,
            action: #selector(onAdd)
        ),UIBarButtonItem(
            title: "-",
            style: .plain,
            target: self,
            action: #selector(onDecrease)
        )]
        
        preprareAudio()
        
        //
        let tickNote = NSNotification.Name(PlayerEventNotification.TickEvent.rawValue)
        NotificationCenter.default.addObserver(self,
                                               selector: #selector(listenTimeTick(note:)),
                                               name: tickNote,
                                               object: nil)
        
        //
        let statusNote = NSNotification.Name(PlayerEventNotification.PlayStatusChanged.rawValue)
        NotificationCenter.default.addObserver(self,
                                               selector: #selector(onStatusChanged(note:)),
                                               name: statusNote,
                                               object: nil)
    }
    
    private func preprareAudio() {
        let session = AVAudioSession.sharedInstance();
        do{
            try session.setActive(true)
            try session.setCategory(AVAudioSession.Category.playback)
            self.player.updateConfigure(self.plans,
                                        duration: duration)
        } catch {
        }
    }
    
    @objc func listenTimeTick(note: Notification) {
        guard let userInfo = note.userInfo,
              let tick: Int = userInfo["tick"] as? Int  else {
            return
        }
        
        DispatchQueue.main.async {
            if #available(iOS 16.0, *) {
                let duraton = Duration.seconds(tick)
                self.lbTime.text = "\(duraton.formatted()) ~ \(self.cmdTitle)"
                self.lbTime.sizeToFit()
            } else {
                // Fallback on earlier versions
            }
        }
        
        debugPrint("tick:\(tick)")
    }
    
    @objc func onStatusChanged(note: Notification) {
        guard let userInfo = note.userInfo,
              let status = userInfo["status"] as? PlayerStatus,
              let tick = userInfo["tick"] as? Int
        else {
            return
        }
        switch status {
        case .paused:
            self.btn.setTitle("播放", for: .normal)
        case .playing:
            self.btn.setTitle("暂停", for: .normal)
        case .stopped:
            debugPrint("stopped \(#function)")
        default:
            break
        }
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    /*
     // MARK: - Navigation
     
     // In a storyboard-based application, you will often want to do a little preparation before navigation
     override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
     // Get the new view controller using segue.destination.
     // Pass the selected object to the new view controller.
     }
     */
}

extension ASMRViewController {
    
    @objc func onAdd() {
        Task {
            self.cmdTitle =  await shuffle(.increase)
        }
    }
    
    @objc func onDecrease() {
        Task {
            self.cmdTitle  =  await shuffle(.decrease)
        }
    }
    
    func shuffle(_ cmd: EnhanceCommand) async -> String {
        do{
            let usr = User()
            let api = TherapyApi()
            //
            let opt: EnhanceCommand = cmd == .increase ?.increase : .decrease
            let plans = try await api.fetchEnhancedSolution(
                usr.userID,
                cure: 483,
                duration: self.duration,
                command: opt)
            
            guard let plans = plans else {
                switch cmd {
                case .decrease:
                    return "减损失败"
                default:
                    return  "增益失败"
                }
            }
            
            try self.player.shuffle(
                plans,
                duration: duration
            ){
                debugPrint("\(#function)")
            }
            
            switch cmd {
            case .decrease:
                return "减损" + timestamp
            default:
                return "增益" + timestamp
            }
        } catch HCPlayerCacheError.WithoutEnoughTime {
            debugPrint("Without Enough Time \(#function) ")
            return "Without Enough Time"
        } catch {
            debugPrint("\(error) \(#function) ")
        }
        return ""
    }
    
    var timestamp: String {
        get {
            // 创建一个 DateFormatter 实例
            let dateFormatter = DateFormatter()
            
            // 设置日期格式为星期的缩写（例如："Mon", "Tue"）
            dateFormatter.dateFormat = "‌‌HH:mm:ss"
            
            // 或者使用当前地区的默认设置：
            dateFormatter.locale = Locale.current
            
            // 创建一个 Date 对象，例如当前日期和时间
            let date = Date()
            
            return dateFormatter.string(from: date)
        }
    }
}

extension ASMRViewController : @preconcurrency CacheFileDelegate{
    @objc func onAllFileDidDownload(_ player: HCAudioPlayer.Player,
                                    succeed: Set<String>,
                                    failed: Set<String>) {
        print(#function)
        player.play()
    }
    
    @objc func onSomeCacheDidFinish(_ player: HCAudioPlayer.Player) {
        print(#function)
        player.play()
    }
    
    @objc func onPressedButton() {
        switch(self.player.status){
        case .playing:
            self.player.pause()
        case .paused:
            self.player.play()
        default:
            debugPrint(#function)
        }
    }
}

